package com.example.systemserver.controller;

import cn.hutool.jwt.JWTUtil;
import com.example.systemserver.bean.RequestBean;
import com.example.systemserver.service.PersonService;
import com.example.systemserver.bean.ResultBean;
import com.example.systemserver.bean.PersonBean;
import com.github.pagehelper.PageInfo;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;
//slf4j日志
@Slf4j
//将PersonController类交给Spring管理并返回json格式的数据
@RestController
//上下线请求的URL地址为/person/。。。为简化写法
@RequestMapping("/person")
//与客户端进行沟通
public class PersonController {
    //json数据格式由大括号和数据组成以逗号分割
    @Autowired
    private PersonService personService;
    @RequestMapping("/save")
    //使用PersonBean接收数据 JSON格式把r传给p
    public ResultBean save(@RequestBody PersonBean requestBean){
        log.info("/person/save,学员保存,请求参数{}",requestBean);
        personService.save(requestBean);
        log.info("/person/save,学员保存完成,返回值:null");
        return new ResultBean(200,"保存成功",null) ;
    }

    @RequestMapping("/remove")
    public ResultBean remove(@RequestBody PersonBean requestBean){
        log.info("/person/remove,学员删除,请求参数{}",requestBean);
        personService.remove(requestBean);
        log.info("/person/remove,学员删除完成,返回值:null");
        return new ResultBean(200,"删除成功",null);
        }

    @RequestMapping("/list")
    public ResultBean list(@RequestBody RequestBean<PersonBean> requestBean , HttpServletRequest servletRequest){
        log.info("/person/list,学员列表查询,请求参数{}",requestBean);
        //在Header中获取token
        String token = servletRequest.getHeader("token");
        //验证token的有效性
//        if (token == null){
//            return new ResultBean(401,"请先登录",null);
//        }
//        try{
//            JWTUtil.verify(token, "1234567".getBytes(StandardCharsets.UTF_8));
//        }catch (Exception e){
//            return new ResultBean(401,"无效的token",null);
//        }

        ResultBean resultBean;
        PageInfo<PersonBean> pageInfo = personService.list(requestBean);
        resultBean =  new ResultBean(200,"查询成功",pageInfo);
        log.info("/person/list,学员列表完成,返回值{}",resultBean);
        return resultBean;
    }

    @RequestMapping("/info")
    public ResultBean info(@RequestBody PersonBean requestBean){
        log.info("/person/info,学员详情,请求参数{}",requestBean);
        ResultBean resultBean;
        PersonBean personBean = personService.info(requestBean);
        resultBean =  new ResultBean(200,"查询成功",personBean);
        log.info("/person/info,学员详情完成,返回值{}",resultBean);
        return resultBean;
    }
}
